package zt.song.shopping.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import zt.song.shopping.domain.User;
import zt.song.shopping.service.UserService;

/**
 * @Author 宋伟宁
 * @Date 2023/12/6
 * @Version 1.0
 **/
@Controller
@Validated
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 注册请求：get
     * @param model
     * @return
     */
    @GetMapping("/register")
    public String save(Model model){
        //后端传递一个用户对象
        model.addAttribute(new User());
        return "register";
    }

    /**
     * 注册处理：post
     * @param user
     * @param br
     * @return
     */
    @PostMapping("/register")
    public String register(@Validated User user, BindingResult br){
         if(br.hasErrors()){
             for(ObjectError err: br.getAllErrors()){
                 System.out.println(err.getDefaultMessage());
             }
             return "register";
         }else{
             this.userService.save(user);
             return "redirect:/login";
         }

    }

    @GetMapping("/login")
    public String tologin(Model model){
        model.addAttribute(new User());
        return "login";
    }

    @PostMapping("/login")
    public String login( User user, HttpSession session,Model model){

            //验证数据库存在账号
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername())
                    .eq("password", user.getPassword());
            User one = this.userService.getOne(queryWrapper);
            if (null == one) {
                model.addAttribute("msg", "<font color='red'>账号或密码错误，登录失败</font>");
                return "login";
            } else {
                //保存到session中
                session.setAttribute("user", one);
            }
            //重定向到商品列表页面
            return "redirect:/list";

    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/login";
    }
}
